import React, { Component } from 'react'

export default class Test extends Component {
    constructor(props) {
        super(props)
        this.state = {
            todoList: [
                {id: 1, name: "aa"},
                {id: 2, name: "bb"},
                {id: 3, name: "cc"},
                {id: 5, name: "ee"},
            ]
        }
    }

    renderTodoList = () => {
        const {todoList} = this.state
        return todoList.map((m, index) => <li key={m.id} >
            <hr />
            <span> {m.name} </span>
            { index !== 0  && <button onClick={() => this.up(index, m)} >上移</button> }
            {( todoList.length-1) !== index && <button onClick={() => this.down(index, m) } >下移</button> }
            <hr />
        </li> )
    }

    up = (index, item) => {  //  上移
        const { todoList } = this.state
        // console.log("向上", index, item)
        todoList.splice(index-1, 0, item)
        // todoList.splice(index, 1)
        // console.log( todoList.lastIndexOf(item), "返回 的是下标" )
        let newIndex = todoList.lastIndexOf(item)
        let aaa = todoList.filter((f, index) => index !== newIndex )
        this.setState({
            todoList: aaa
        })
    }

    down = (index, item) => {
        const { todoList } = this.state
        // console.log("向下", index, item)
        todoList.splice(index+2, 0, item)
        let newIndex = todoList.indexOf(item)
        // console.log("newIndex", newIndex)
        let aaa = todoList.filter((f, index) => index !== newIndex )
        this.setState({
            todoList: aaa
        })
    }
  render() {
    return (
      <div>
          <ul>
              {this.renderTodoList()}
          </ul>
      </div>
    )
  }
}
